package cn.edu.tju.core.security.service;

import cn.edu.tju.core.model.User;
import cn.edu.tju.elm.model.DTO.UserDTO;
import cn.edu.tju.elm.model.entity.UserProfile;
import cn.edu.tju.elm.repository.UserProfileRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
@Transactional
@RequiredArgsConstructor
public class UserProfileService {

    private final UserProfileRepository userProfileRepository;
    private final UserService userService;

    public UserDTO getCurrentUserProfile() {
        User user = userService.getUserWithAuthorities();
        UserProfile userProfile = userProfileRepository.findById(user.getId())
                .orElse(new UserProfile());

        return buildUserDTO(user, userProfile);
    }

    public UserDTO updateUserAvatar(String avatarUrl) {
        User user = userService.getUserWithAuthorities();
        UserProfile userProfile = userProfileRepository.findById(user.getId())
                .orElse(UserProfile.builder().id(user.getId()).build());

        userProfile.setAvatarUrl(avatarUrl);
        userProfile.setUser(user);
        userProfile.setUsername(user.getUsername());

        LocalDateTime now = LocalDateTime.now();
        userProfile.setUpdateTime(now);
        userProfile.setUpdater(user.getId());

        // 如果新增，设置创建时间
        if (userProfile.getCreateTime() == null) {
            userProfile.setCreateTime(now);
            userProfile.setCreator(user.getId());
        }

        UserProfile savedProfile = userProfileRepository.save(userProfile);
        return buildUserDTO(user, savedProfile);
    }

    private UserDTO buildUserDTO(User user, UserProfile userProfile) {
        return UserDTO.builder()
                .id(user.getId())
                .username(user.getUsername())
                .authorities(user.getAuthorities())
                .avatarUrl(userProfile.getAvatarUrl())
                .bio(userProfile.getBio())
                .birthday(userProfile.getBirthday())
                .build();
    }
}